<template>
  <AdVxeModal
    v-bind="$attrs"
    @register="register"
    :id="formIndex"
    :title="`${t('iot.route.driver.title')} - ${FormModeEntityRef.Display}`"
    :help-message="`${t('common.form')}：${formIndex}`"
    :cancel-text="t('common.cancelText')"
    :close-func="handleClose"
    :ok-text="FormModeEntityRef.OkBtnTitle"
    @ok="handleOk"
    @open-change="handleOpenChange"
    width="50%"
  >
    <BasicForm @register="registerForm" @contextmenu="handleContextMenu">
      <template #packageContent="{ model, field }">
        <UploadDragger
          v-model:value="model[field]"
          accept=".zip"
          :disabled="
            FormModeEntityRef.FormMode !== FormModeEnum.Add && FormModeEntityRef.FormMode !== FormModeEnum.Edit
          "
          :description="t('iot.route.driver.package.uploadHelpText')"
          @change="handleUploadChange"
        />
      </template>
    </BasicForm>
    <template #insertFooter>
      <Authority value="Root.IoT.Admin.Driver.GetPackage">
        <a-button color="success" @click="handleDownloadPackage" :loading="loadingRef">
          <Icon icon="mdi:download-circle-outline" />
          {{ t('iot.route.driver.downloadPackage') }}
        </a-button>
      </Authority>
      <Authority value="Root.IoT.Admin.Driver.SetPackage">
        <a-button
          color="warning"
          @click="handleSetPackage"
          v-if="FormModeEntityRef.FormMode === FormModeEnum.Edit"
          :loading="loadingRef"
        >
          <Icon icon="clarity:update-line" />
          {{ t('iot.route.driver.setPackage') }}
        </a-button>
      </Authority>
      <Authority value="Root.IoT.Admin.Driver.UpdateSimple">
        <a-button
          color="warning"
          @click="handleUpdateSimple"
          v-if="FormModeEntityRef.FormMode === FormModeEnum.Edit"
          :loading="loadingRef"
        >
          <Icon icon="clarity:note-edit-line" />
          {{ t('iot.route.driver.updateSimple') }}
        </a-button>
      </Authority>
    </template>
  </AdVxeModal>

  <PrintTemplateModal @register="templateModalRegister" v-bind="templateModalProps" />
</template>

<script lang="ts" setup>
  import type { DriverInputDto, DriverOutputDto, DriverPackageInputDto } from '@/api/iot/admin/driver/model';
  import type { FormSchema } from '@/components/Form';

  import type { PropType } from 'vue';

  import type { AjaxResult } from '#/request';

  import { ref } from 'vue';

  import { isFunction } from '@eacloud/utils';

  import {
    createDriver,
    deleteDriver,
    getDriverPackage,
    setDriverPackage,
    updateDriver,
    updateDriverSimple,
  } from '@/api/iot/admin/driver';
  import { PrintTemplateModal, useAdPrint } from '@/components/AdPrint';
  import { AdVxeModal, useModalInner } from '@/components/AdVxeModal';
  import { Authority } from '@/components/Authority';
  import { destroyContextMenu } from '@/components/ContextMenu';
  import { BasicForm, useForm } from '@/components/Form';
  import Icon from '@/components/Icon/Icon.vue';
  import { UploadDragger } from '@/components/UploadDragger';
  import { FormModeEntity, FormModeEnum } from '@/enums/formEnum';
  import { useContextMenu } from '@/hooks/web/useContextMenu';
  import { useI18n } from '@/hooks/web/useI18n';
  import { downloadByBase64 } from '@/utils/file/download';

  defineOptions({ name: 'DriverDetailModal' });
  const props = defineProps({
    /** 关闭回调，返回true关闭窗体 */
    closeFunc: {
      type: Function as PropType<(formMode: FormModeEnum, record?: DriverOutputDto) => Promise<boolean>>,
      default: null,
    },
    /** 提交前回调，返回false不执行内置提交逻辑，返回true执行内置提交逻辑 */
    beforeSubmitFunc: {
      type: Function as PropType<(formMode: FormModeEnum, record?: DriverOutputDto) => Promise<boolean>>,
      default: null,
    },
    /** 提交后回调，返回true关闭窗体 */
    afterSubmitFunc: {
      type: Function as PropType<
        (formMode: FormModeEnum, result?: AjaxResult | null, record?: DriverOutputDto) => Promise<boolean>
      >,
      default: null,
    },
  });

  const { t } = useI18n();
  const { createContextMenu } = useContextMenu();
  const formIndex = 'iot_driver_detail';
  const keyField = 'Id';

  const formModeRef = ref<FormModeEnum>(FormModeEnum.Ok);
  const FormModeEntityRef = ref<FormModeEntity>(new FormModeEntity(formModeRef.value));

  const schemas: FormSchema[] = [
    {
      field: 'Id',
      helpMessage: `${t('common.field')}：${'Id'}`,
      component: 'Input',
      label: t('entity.idTitle'),
      componentProps: { disabled: true },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'Name',
      helpMessage: `${t('common.field')}：${'Name'}`,
      component: 'Input',
      label: t('iot.route.driver.nameText'),
      required: true,
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'Description',
      helpMessage: `${t('common.field')}：${'Description'}`,
      component: 'Input',
      label: t('iot.route.driver.descriptionText'),
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'StartupFile',
      helpMessage: `${t('common.field')}：${'StartupFile'}`,
      component: 'Input',
      label: t('iot.route.driver.startupFileText'),
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'StartupClass',
      helpMessage: `${t('common.field')}：${'StartupClass'}`,
      component: 'Input',
      label: t('iot.route.driver.startupClassText'),
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'PackagePath',
      helpMessage: `${t('common.field')}：${'PackagePath'}`,
      component: 'Input',
      label: t('iot.route.driver.packagePathText'),
      colProps: {
        // span: 24,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 24, // ≥1200px
        xxl: 24, // ≥1600px
        // xxxl: 24, // ≥2000px 3.0
      },
    },
    {
      field: 'Enabled',
      helpMessage: `${t('common.field')}：${'Enabled'}`,
      component: 'Switch',
      label: t('iot.route.driver.enabledText'),
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'Remark',
      helpMessage: `${t('common.field')}：${'Remark'}`,
      component: 'InputTextArea',
      label: t('iot.route.driver.remarkText'),
      colProps: {
        // span: 24,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 24, // ≥1200px
        xxl: 24, // ≥1600px
        // xxxl: 24, // ≥2000px 3.0
      },
    },
    { field: 'divider-basic', component: 'Divider', label: '', colProps: { span: 24 } },
    {
      field: 'Package.Id',
      helpMessage: `${t('common.field')}：${'Package.Id'}`,
      component: 'Input',
      label: t('entity.idTitle'),
      required: true,
      ifShow: false,
      componentProps: { disabled: true },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'Package.DriverId',
      helpMessage: `${t('common.field')}：${'Package.DriverId'}`,
      component: 'Input',
      label: t('iot.route.driver.package.driverIdText'),
      required: true,
      ifShow: false,
      componentProps: { disabled: true },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'Package.Content',
      helpMessage: `${t('common.field')}：${'Package.Content'}`,
      // component: 'InputTextArea',
      slot: 'packageContent',
      label: t('iot.route.driver.package.title'),
      colProps: {
        // span: 24,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 24, // ≥1200px
        xxl: 24, // ≥1600px
        // xxxl: 24, // ≥2000px 3.0
      },
    },
    {
      field: 'Package.Name',
      helpMessage: `${t('common.field')}：${'Package.Name'}`,
      component: 'Input',
      label: t('iot.route.driver.package.nameText'),
      componentProps: { disabled: true },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'Package.Content',
      helpMessage: `${t('common.field')}：${'Package.Content'}`,
      component: 'InputTextArea',
      label: t('iot.route.driver.package.contentText'),
      componentProps: { disabled: true },
      ifShow: false,
    },
    {
      field: 'Package.Description',
      helpMessage: `${t('common.field')}：${'Package.Description'}`,
      component: 'Input',
      label: t('iot.route.driver.package.descriptionText'),
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'Package.Remark',
      helpMessage: `${t('common.field')}：${'Package.Remark'}`,
      component: 'InputTextArea',
      label: t('iot.route.driver.package.remarkText'),
      colProps: {
        // span: 24,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 24, // ≥1200px
        xxl: 24, // ≥1600px
        // xxxl: 24, // ≥2000px 3.0
      },
    },
    { field: 'divider-basic', component: 'Divider', label: '', colProps: { span: 24 } },
    {
      field: 'CreatedTime',
      helpMessage: `${t('common.field')}：${'CreatedTime'}`,
      component: 'DatePicker',
      label: t('entity.creationAudited.createdTimeTitle'),
      componentProps: {
        disabled: true,
        showTime: true,
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        style: { width: '100%' },
      },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'UpdatedTime',
      helpMessage: `${t('common.field')}：${'UpdatedTime'}`,
      component: 'DatePicker',
      label: t('entity.updateAudited.updatedTimeTitle'),
      componentProps: {
        disabled: true,
        showTime: true,
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        style: { width: '100%' },
      },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
  ];

  const [registerForm, { resetFields, getFieldsValue, setFieldsValue, validate }] = useForm({
    labelWidth: 150,
    schemas,
    showActionButtonGroup: false,
    compact: true,
  });

  const [register, { setModalProps, closeModal, changeLoading }] = useModalInner(async (data) => {
    changeLoading(true);
    try {
      await clearInputDto();
      let record = (data?.record || {}) as DriverOutputDto;
      if (data.formMode) {
        formModeRef.value = data.formMode as FormModeEnum;
        FormModeEntityRef.value = new FormModeEntity(formModeRef.value);
        switch (formModeRef.value) {
          case FormModeEnum.Add:
            break;
          case FormModeEnum.Edit:
          case FormModeEnum.ReadOnly:
          case FormModeEnum.Ok:
            if (record?.Id) {
              const result = await getDriverPackage(record.Id);
              if (result) {
                const packageOutputDto = result;
                // console.log(packageOutputDto);
                if (packageOutputDto) {
                  record = { ...record, Package: { ...packageOutputDto } };
                }
              }
            }

            break;
        }
      }
      if (record) {
        await setInputDto({
          ...record,
        });
      }
    } finally {
      changeLoading(false);
    }
  });

  // #region "加载状态"
  const loadingRef = ref(false);
  /** 开启加载状态 */
  function openLoading() {
    changeLoading(true);
    setModalProps({ okLoading: true, cancelLoading: true });
    loadingRef.value = true;
  }
  /** 关闭加载状态 */
  function closeLoading() {
    changeLoading(false);
    setModalProps({ okLoading: false, cancelLoading: false });
    loadingRef.value = false;
  }
  // #endregion
  // #region 定义高级打印
  const { printContextMenus, templateModalRegister, templateModalProps } = useAdPrint({
    formIndex,
    keyField,
    getFormData: () => getFieldsValue(),
  });
  /** 处理上下文菜单(右键菜单) */
  function handleContextMenu(e: MouseEvent) {
    const element = document.elementFromPoint(e.clientX, e.clientY) as Element;
    const cursor = document.defaultView?.getComputedStyle(element, null).cursor;
    // console.log('handleContextMenu', {
    //   cursor: cursor,
    // });

    let items: any[] = [];
    switch (FormModeEntityRef.value.FormMode) {
      case FormModeEnum.Ok:
      case FormModeEnum.Edit:
      case FormModeEnum.ReadOnly:
        if (!cursor || cursor === 'default' || cursor === 'auto') {
          items = [...printContextMenus];
        }
        break;
    }
    if (items && items?.length > 0) {
      createContextMenu({
        event: e,
        styles: {
          border: '1px solid #eee',
          'border-radius': '2px',
          'box-shadow': '3px 3px 3px rgb(0 0 0 / 15%)',
        },
        items: [...items],
      });
    }
  }
  // #endregion

  /** 获取输入DTO */
  function getInputDto(): DriverInputDto {
    const record = getFieldsValue() as DriverInputDto;
    if (record.Package) {
      record.Package.DriverId = record.Id;
    }
    return record;
  }
  /** 设置输入DTO */
  async function setInputDto(values: any) {
    let inputDto = getInputDto();
    inputDto = { ...inputDto, ...values };
    await setFieldsValue({ ...inputDto });
  }
  /** 清除输入DTO */
  async function clearInputDto() {
    await resetFields();
  }

  /** 获取输出DTO */
  function getOutputDto(): DriverOutputDto {
    const record = getFieldsValue() as DriverOutputDto;
    return record;
  }

  /** 文件上传触发 */
  async function handleUploadChange({ value, fileInfo }: { value: string; fileInfo: any }) {
    // console.log('handleUploadChange', { value, fileInfo });
    if (value && fileInfo) {
      const inputDto = getInputDto();
      inputDto.Package = {
        ...inputDto.Package,
        Name: fileInfo.name,
        Content: value,
      } as DriverPackageInputDto;
      await setInputDto(inputDto);
    }
  }

  /** 处理关闭按钮 */
  async function handleClose() {
    openLoading();

    const { closeFunc } = props;
    try {
      if (closeFunc && isFunction(closeFunc)) {
        const outputDto = getOutputDto();
        const result = await closeFunc(FormModeEntityRef.value.FormMode, outputDto);
        return result;
      }
    } finally {
      closeLoading();
    }
    return true;
  }
  /** 处理确定按钮 */
  async function handleOk() {
    const data = await validate();
    if (!data) return;
    // console.log(data);

    openLoading();
    const { beforeSubmitFunc, afterSubmitFunc } = props;
    try {
      const inputDto = getInputDto();
      const outputDto = getOutputDto();
      // console.log('handleOk', inputDto);
      let innerSubmit = true;
      let innerCloseModal = true;
      if (beforeSubmitFunc && isFunction(beforeSubmitFunc)) {
        innerSubmit = await beforeSubmitFunc(FormModeEntityRef.value.FormMode, outputDto);
      }
      let result: AjaxResult | null = null;
      if (innerSubmit) {
        switch (FormModeEntityRef.value.FormMode) {
          case FormModeEnum.Add:
            result = await createDriver([inputDto]);
            break;
          case FormModeEnum.Edit:
            result = await updateDriver([inputDto]);
            break;
          case FormModeEnum.Delete:
            result = await deleteDriver([inputDto.Id]);
            break;
        }
      }
      if (afterSubmitFunc && isFunction(afterSubmitFunc)) {
        innerCloseModal = await afterSubmitFunc(FormModeEntityRef.value.FormMode, result, outputDto);
      }
      if (innerCloseModal) {
        closeModal();
      }
    } finally {
      closeLoading();
    }
  }

  /** 处理设置程序包 */
  async function handleDownloadPackage() {
    openLoading();
    try {
      const inputDto = getInputDto();
      // console.log('inputDto', inputDto);
      if (inputDto?.Package?.Name && inputDto?.Package?.Content) {
        downloadByBase64(inputDto.Package.Content, inputDto.Package.Name);
      }
    } finally {
      closeLoading();
    }
  }
  /** 处理设置程序包 */
  async function handleSetPackage() {
    const { afterSubmitFunc } = props;
    if (FormModeEntityRef.value.FormMode === FormModeEnum.Edit) {
      openLoading();
      try {
        const inputDto = getInputDto();
        const outputDto = getOutputDto();
        const packageDto = inputDto.Package || ({} as DriverPackageInputDto);
        packageDto.DriverId = inputDto.Id;
        // console.log('handleOk', inputDto);
        let innerCloseModal = true;
        const reulst = await setDriverPackage([packageDto]);
        if (afterSubmitFunc && isFunction(afterSubmitFunc)) {
          innerCloseModal = await afterSubmitFunc(FormModeEntityRef.value.FormMode, reulst, outputDto);
        }
        if (innerCloseModal) {
          closeModal();
        }
      } finally {
        closeLoading();
      }
    }
  }
  /** 处理更新驱动简单信息 */
  async function handleUpdateSimple() {
    const data = await validate();
    if (!data) return;

    const { afterSubmitFunc } = props;
    if (FormModeEntityRef.value.FormMode === FormModeEnum.Edit) {
      openLoading();
      try {
        const inputDto = getInputDto();
        const outputDto = getOutputDto();
        // console.log('handleOk', inputDto);
        let innerCloseModal = true;
        const reulst = await updateDriverSimple([inputDto]);
        if (afterSubmitFunc && isFunction(afterSubmitFunc)) {
          innerCloseModal = await afterSubmitFunc(FormModeEntityRef.value.FormMode, reulst, outputDto);
        }
        if (innerCloseModal) {
          closeModal();
        }
      } finally {
        closeLoading();
      }
    }
  }

  /** 打开或者关闭触发 */
  function handleOpenChange(open: boolean) {
    if (!open) {
      destroyContextMenu();
    }
  }
</script>

<style lang="scss" scoped></style>
